<?php
/**
 * @link http://www.ptphp.com
 * @copyright Copyright (c) 2012 PtPHP Software LLC
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @author joseph <ptphp@qq.com>
 */

namespace pt;
require_once PATH_SRC_PHP_LIB.'/aliyun-oss/autoload.php';
use Exception;
use OSS\OssClient as OssClient;
use OSS\Core\OssException as OssException;

/*
 *
pt\AliyunOss::$config = array(
    'default'=>array(
        "accessKeyId"=>"",
        "accessKeySecret"=>"",
        "endpoint"=>"",
    )
);

$ossClient = pt\AliyunOss::init();
echo $ossClient->uploadContent("tcpmobile","tre.jpg","hello");


 */
class AliyunOss{
    private $instance;
    static $config = array(
        'default'=>array(
            "accessKeyId"=>"",
            "accessKeySecret"=>"",
            "endpoint"=>"",
        )
    );
    private $curConfig;

    private static $_obj = array();
    private function __construct($key)
    {
        $this->config($key);
    }

    public static function init($key = 'default')
    {
        if(!empty(\App::$config['AliyunOss'])){
            self::$config = \App::$config['AliyunOss'];
        }
        if(empty(self::$_obj[$key]))
        {
            return self::$_obj[$key] = new AliyunOss($key);
        }
        return self::$_obj[$key];
    }
    public function close(){
        echo "close";
    }

    public function config($key){
        if(empty(self::$config[$key])){
            throw new Exception("no config find in setting");
        }

        $this->curConfig = $_config = self::$config[$key];
        $accessKeyId     = $_config['accessKeyId'];
        $accessKeySecret = $_config['accessKeySecret'];
        $endpoint        = $_config['endpoint'];
        try{
            $this->instance = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        }catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    function getBucket(){
        return $this->curConfig['bucket'];
    }
    function uploadContent($object,$content,$isSsl=false){
        $bucket = $this->getBucket();
        $this->instance->putObject($bucket, $object, $content);
        return ($isSsl ? "https://" : "http://") .$bucket.".".$this->curConfig['endpoint']."/".$object;
    }

}